package com.zwjstudy.cachestudy.jetcache.service.impl;


import com.alicp.jetcache.anno.CachePenetrationProtect;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.zwjstudy.cachestudy.jetcache.entity.Company;
import com.zwjstudy.cachestudy.jetcache.service.CompanyService;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * ClassName: CompanyServiceImpl
 * Package: com.zwjstudy.cachestudy.springcache.caffeine.service.impl
 * Description:
 *
 * @Author: 张文俊
 * @Create: 2025-09-20 - 11:36
 * @Version: v1.0
 */
@Service
public class CompanyServiceImpl implements CompanyService {
    @Override
    // 使用 @Cached 注解并指定 cacheType 为 BOTH
    @Cached(area = "companyCache",
            name = "companyCache:",
            key = "#id",
            //expire = 600,
            cacheNullValue = true,//防止缓存穿透
            condition = "#id != null",
            cacheType = CacheType.BOTH
    )
    @CachePenetrationProtect // 添加此注解启用本地锁保护，防止缓存击穿
    public Company getById(Long id) {

        if (id == null) {
            // 记录日志或抛出有意义的业务异常，而不是等到SpEL解析时报错
            throw new IllegalArgumentException("User parameter cannot be null");
        }

        int i = new Random().nextInt(60);

        Company company=new Company(id,"大连广场"+i);
        System.out.println("加载最新的企业数据到缓存中"+company);


        return company;
    }
}
